package com.wx.controller;

import com.wx.model.Param;
import com.wx.repository.UserRepository;
import com.wx.service.WXService;
import com.wx.util.ResultObject;
import com.wx.util.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/9/28 2:49 下午
 * @desc ：
 */
@Slf4j
@RestController
@RequestMapping("/wx")
public class WXController {

    @Autowired
    WXService wxService;
    @Autowired
    UserRepository repository;
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * timestamp	时间戳
     * nonce	随机数
     * echostr	随机字符串
     *
     * 开发者通过检验signature对请求进行校验（下面有校验方式）。
     * 若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。
     * @return
     */
    @GetMapping
    public String method1(Param param) throws IOException {
        System.out.println("param:"+param);
        if(wxService.check(param)){
            System.out.println("接入成功");
            //原样返回
            return param.getEchostr();
        }else {
            System.out.println("接入失败");
            return null;
        }
    }

    /**
     * 处理消息和事件推送
     * @param request
     * @throws IOException
     */
    @PostMapping
    public String method2(HttpServletRequest request) throws IOException {

        Map<String,String> map = wxService.parseRequest(request.getInputStream());
        System.out.println("处理消息和事件推送:"+map);
        log.error("处理消息和事件推送:"+map);
        return wxService.getRespose(map);
    }

    /**
     * http://wangyitong.club/wx/findAllUser/
     * @return
     */
    @GetMapping("/findAllUser")
    public ResultObject findAllUser(){
//        List<User> all = repository.findAll();
//        log.error("error");
//        log.info("info");
//        log.warn("warn");
//        log.trace("trace");
        return new ResultObject(true, StatusCode.OK,"查询成功","SUCCESS");

    }
    @GetMapping("/testRedis")
    public ResultObject testRedis(){
        Long testRedis = redisTemplate.opsForValue().increment("testRedis");
        return new ResultObject(true, StatusCode.OK,"Redis连接成功",testRedis);
    }


}
